<template>
  <div class="home">
    <!-- loading start -->
    <loading v-if="showLoading" />
    <!-- loading end -->
    <!-- 背景音效-->
    <audioGroup ref="audioGroup"></audioGroup>
    <!-- 首页初始化弹出层-->
    <home-page-dialog
      ref="homePageDialog"
      :showCover="showCover"
      :reason_to_showDialog="reason_to_showDialog"
      :userTime="userTime"
      @goNow="goNow"
      @goAction="goAction"
    ></home-page-dialog>
    <!--推荐框弹出层-->
    <van-overlay :show="showAdvice">
      <div class="wrapper">
        <div class="advice_content" v-if="showAdvice">
          <div class="close_advice" @click="close_advice"></div>
          <div class="btn_group">
            <div v-for="i in 3" :key="i" @click="goNow(i)"></div>
          </div>
        </div>
      </div>
    </van-overlay>
    <!-- 游戏界面弹出层-->
    <inner-game-dialog
      :showDialog="showDialog"
      :reason_to_show-dialog="reason_to_showDialog"
      :over_time_exit="over_time_exit"
      :today_stage_index="today_stage_index"
      :total_reward="total_reward"
      @back_to_hall="back_to_hall"
      @refresh_page="refresh_page"
      @next_challenge="next_challenge"
      @refresh_game="refresh_game"
      @continue_game="continue_game"
    ></inner-game-dialog>

    <!-- 返回按钮-->
    <div class="back" @click="goback"></div>
    <!-- 游戏界面-->
    <div class="game_container">
      <div class="game_frame">
        <!-- 游戏界面顶部-->
        <div class="top">
          <div class="now">
            <div>
              <div class="first_col">
                <img src="../../img/di.png" /><span>{{
                  today_stage_index + 1
                }}</span
              ><img src="../../img/guan.png" />
              </div>
              <div class="second_col">
                <img src="../../img/reward.png" /><img
                src="../../img/diamand.png"
              /><span>{{ current_reward }}</span>
              </div>
            </div>
          </div>
          <div class="total">
            <div class="total_num">{{ total_reward }}</div>
          </div>
          <div class="count">
            <div class="count_num">
              <van-count-down
                @change="onCountDownChange"
                ref="countDown"
                seconds
                :time="time"
                :auto-start="auto"
                format="mm:ss"
                @finish="finished"
              />
            </div>
          </div>
        </div>
        <!-- 游戏界面图片部-->
        <div class="content">
          <!-- 局部刷新loading-->
          <div class="loading-overlay" v-if="loading_of_pic">
            <div class="loading-content">
              <div class="loading-indicator"></div>
              <span>加载中...</span>
            </div>
          </div>
          <div class="left_content" id="left">
            <!-- 照片1图层 +照片1点击正确图层-->
            <canvas
              class="canvas1"
              ref="canvas1"
              :width="canvas1W"
              :height="canvas1H"
              @click="getCanvasCoordinates($event)"
            ></canvas>
            <!-- 照片1点击错误图层 -->
            <canvas
              class="canvas5"
              ref="canvas5"
              :width="canvas1W"
              :height="canvas1H"
              @click="getCanvasCoordinates($event)"
            ></canvas>
            <!-- 照片1-2s图层 -->
            <canvas
              class="canvas7"
              ref="canvas7"
              :width="canvas1W"
              :height="canvas1H"
              @click="getCanvasCoordinates($event)"
            ></canvas>
          </div>
          <div class="middle"></div>
          <div class="right_content" id="right">
            <!-- 照片2图层 +照片2点击正确图层-->
            <canvas
              class="canvas2"
              ref="canvas2"
              :width="canvas2W"
              :height="canvas2W"
              @click="getCanvasCoordinates($event)"
            ></canvas>
            <!-- 照片2点击错误图层 -->
            <canvas
              class="canvas6"
              ref="canvas6"
              :width="canvas2W"
              :height="canvas2W"
              @click="getCanvasCoordinates($event)"
            ></canvas>
            <!-- 照片2-2s图层 -->
            <canvas
              class="canvas8"
              ref="canvas8"
              :width="canvas2W"
              :height="canvas2H"
              @click="getCanvasCoordinates($event)"
            ></canvas>
          </div>
        </div>
        <!-- 游戏界面底部-->
        <div class="bottom">
          <div class="refresh" @click="refresh_current_pic"></div>
          <div class="tips">
            <img
              v-for="(item, index) in tipsGroup"
              :key="index"
              :src="item.picUrl"
            />
          </div>
          <div class="set">
            <img src="../../img/tip_dark.png" v-if="setting1 <= 0" />
            <img src="../../img/tip.png" @click="useTip" v-else />
            <img src="../../img/time_dark.png" v-if="setting2 <= 0" />
            <img src="../../img/time.png" @click="addTime" v-else />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import loading from '@/components/loading';
import wrong from '../../img/wrong.png';
import correct from '../../img/correct.png';
import animationTime from '../../img/fa.png';
import pick_right from '../../img/pick_right.png';
import pick_wrong from '../../img/pick_wrong.png';
import innerGameDialog from '../../component/innerGameDialog.vue';
import audioGroup from '../../component/audioGroup.vue';
import homePageDialog from '../../component/homePageDialog.vue';
import {
  geConfig,
  getUserDetails,
  challengeStage,
  isPassStage,
  useProp,
  finishGame
} from '../../api/index';

export default {
  components: { loading, innerGameDialog, audioGroup, homePageDialog },
  name: 'Home',

  props: {},
  data() {
    return {
      showLoading: false,
      //处理图片加载慢问题 -----------------------------预加载下两张图片(不管是否通关)
      preload_pic_list: [],
      //单次闯关总奖励
      total_reward: 0,
      //游戏状态
      status: 1,
      //游戏配置id
      gameConfigId: '',
      //当前闯关关数id
      currentStage: null,
      //当前闯关关数属于今天第几关
      today_stage_index: null,
      //动效时长
      animationTime_url: animationTime,
      //选择错误图片路径
      pick_wrong_url: pick_wrong,
      //选择正确图片路径
      pick_right_url: pick_right,
      auto: false,
      noTip: false,
      noAddTime: false,
      canvas1W: 0,
      canvas1H: 0,
      canvas2W: 0,
      canvas2H: 0,
      //用户所剩游戏次数
      userTime: null,
      //调用接口获得用户道具剩余次数(道具1)
      setting1: 0,
      //模拟调用接口获得用户道具剩余次数(道具2)
      setting2: 0,
      //延迟时间
      delayTimeSec: 0,
      //用户所有关数配置表
      userPicGroup: [],
      //模拟数据---------调用接口获得用户本次关数数组
      userRange: [],
      //初始化显示弹出框
      showCover: true,
      //游戏界面显示弹出框
      showDialog: false,
      //触发游戏界面弹出框事件序列 0:中途退出 1:每过一关-还有关卡 2:倒计时结束-还有挑战次数 3:倒计时结束-没有有挑战次数或已过20关 4:挑战完所有关卡或全部剩余不足10关 5:已过零点-结算弹窗
      reason_to_showDialog: null,
      //计时器
      time: 0,
      //页面显示图片数据
      picGroup: [],
      //命中坐标
      positionGroup: [],
      //当前关数----------用户界面
      processNum: null,
      //当前关数用户点击了多少个正确答案
      clickRightNum: 0,
      //标题栏标志用户选对了几个代表的图片数组
      tipsGroup: [],
      //剩余时间秒数
      remainTime: 0,
      data: null,
      //过关时间
      passStageTimeSec: 0,
      //过关延迟时间
      passStageDelayTimeSec: 0,
      //倒计时是否结束
      isFinished: Boolean,
      //定时器
      interval: null,
      //进入页面的时间--------埋点
      user_in_time: null,
      //离开页面的时间--------埋点
      user_off_time: null,
      //两张图片是否都已渲染完标志位----------------防止用户提前点击
      both_rendered: Boolean,
      //过零点后是否退出
      over_time_exit: false,
      //图片loading
      loading_of_pic: false,
      //本关两张图片数组-----------------------图片预加载
      show_pic_group: [],
      //奖励配置标
      contPassRewards: {},
      //本关奖励
      current_reward: 0,
      //每关需要的正确数
      request_right_num: 0,
      //推荐弹窗
      showAdvice: false,
      //是否显示过推荐
      isShowAdvice: false,
      //用户连续挑战成功数量
      user_win_game_num: 0
    };
  },
  watch: {
    clickRightNum: {
      handler(newVal, oldVal) {
        for (const i in this.tipsGroup) {
          if (i == newVal - 1) {
            this.tipsGroup[i].flag = true;
            this.tipsGroup[i].picUrl = correct;
          }
        }
        if (newVal >= this.request_right_num) {
          this.notice_challenge_result(1);
          this.auto = false;
          if (document.getElementById('fly_diamand1')) {
            document
              .getElementById('fly_diamand1')
              .parentNode.removeChild(document.getElementById('fly_diamand1'));
          }
        }
      }
    }
  },
  created() {
  },
  mounted() {
    //原生设置
    this.native_setting();
    //获取配置表
    this.geConfig();
    //解决锁屏继续播放音效
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState !== 'visible') {
        this.$refs.audioGroup.$refs.bgAudio.pause();
      }
    });
  },
  methods: {
    //调用原生跳转到游戏桌
    async sendParamToNative(gameId) {
      this.$refs.audioGroup.$refs.bgAudio.pause();
      this.$refs.audioGroup.$refs.congratulationAudio.pause();
      this.$refs.audioGroup.$refs.gameoverAudio.pause();
      await Promise.resolve(
        this.$bridge.callHandler(
          'h5_open_mj_game',
          {
            kindId: gameId, /// 游戏id：决斗麻将 454；妞妞 456； 四无双 451
            voiceId: ''
          }, /// 语音房id，可不传 },
          data => {
          }
        )
      );

      await Promise.resolve(
        this.$bridge.callHandler(
          'cancel_mute_game_sound',
          { force: 1 },
          data => {
          }
        )
      );
      this.$bridge.callHandler('close', {}, data => {
      });
    },
    //点击立即前往
    goNow(i) {
      console.log(i);
      switch (i) {
        case 1:
          this.sendParamToNative(454);
          break;
        case 2:
          this.sendParamToNative(456);
          break;
        case 3:
          this.sendParamToNative(451);
          break;
      }
    },
    //关闭推荐弹窗
    close_advice() {
      this.showAdvice = false;
      if (this.isFinished) {
        this.showDialog = true;
        //判断用户触发弹窗事件 (有没有挑战次数)
        if (this.userTime > 0) {
          this.reason_to_showDialog = 2;
          //失败播放失败音效
          this.$refs.audioGroup.$refs.gameoverAudio.currentTime = 0;
          this.$refs.audioGroup.$refs.gameoverAudio.play();
        } else {
          this.reason_to_showDialog = 3;
        }
      } else {
        //每过一关展示弹窗
        this.showDialog = true;
        this.reason_to_showDialog = 1;
        //过关播放过关音效
        this.$refs.audioGroup.$refs.congratulationAudio.currentTime = 0;
        this.$refs.audioGroup.$refs.congratulationAudio.play();
        //调用飞钻石
        this.$nextTick(() => {
          this.create_element_diamand();
          this.moveElement('fly_diamand1', 20, 20);
        });
        this.$refs.countDown.pause();
      }
    },

    //刷新本关图片
    refresh_current_pic() {
      this.loading_of_pic = false;
      //如果两张图片均加载则点击无反应
      if (!this.both_rendered) {
        this.loading_of_pic = true;
        this.drawImage();
      }
    },
    //刷新页面
    refresh_page() {
      location.reload();
    },
    //原生设置
    native_setting() {
      //背景声音静音
      this.$bridge.callHandler('mute_game_sound', { force: 1 }, data => {
      });
      //隐藏返回按钮
      this.$bridge.callHandler(
        'hide_and_show_back_btn',
        { isHidden: 1 },
        data => {
        }
      );
    },
    // 预加载图片
    loadPic(processNum) {
      this.userPicGroup[processNum].picGroup.forEach(item => {
        const img = new Image();
        img.src = item;
        img.setAttribute('crossorigin', '');
        img.onload = () => {
        };
      });
    },
    //获取配置表
    geConfig() {
      this.showLoading = true;
      geConfig().then(res => {
        console.log('获取配置表接口返回-----------------' + res.errorMsg);
        this.showLoading = false;
        if (res.errorCode == 0) {
          res.data.h5ConfigJsonCorrect = JSON.parse(res.data.h5ConfigJson);
          this.data = res.data.h5ConfigJsonCorrect;
          this.contPassRewards = res.data.contPassRewards;
          this.data.forEach(item => {
            item.picGroup.forEach((childrenItem, index) => {
              childrenItem =
                'https://img.plchat.com/10001/minigame/finddiff-v4/' +
                childrenItem +
                '.jpg';
              item.picGroup[index] = childrenItem;
            });
          });
          this.passStageTimeSec = res.data.passStageTimeSec * 1000;
          this.passStageDelayTimeSec = res.data.passStageDelayTimeSec;
          this.getUserData();
        } else {
          this.$toast(res.errorMsg);
        }
      });
    },
    //获取用户信息
    getUserData() {
      getUserDetails().then(res => {
        console.log('获取用户信息接口返回-----------------' + res.errorMsg);
        if (res.errorCode == 0) {
          this.gameConfigId = res.data.gameConfigId;
          this.userTime = res.data.challengeTimes;
          this.status = res.data.status;
          this.userRange = res.data.stages;
          this.currentStage = res.data.currentStage;
          //用户当日挑战完20关
          if (res.data.currentStage == 0) {
            this.reason_to_showDialog = 3;
          }
          //调用接口获得用户当日20关数据
          var userAllPicGroups = [];
          for (var item of this.userRange) {
            this.data.forEach(picItem => {
              if (picItem.num == item) {
                userAllPicGroups.push(picItem);
              }
            });
          }
          //根据返回字段(当前关数)获得用户未完成关卡数组
          userAllPicGroups.forEach((item, index) => {
            if (item.num == this.currentStage) {
              this.userPicGroup = userAllPicGroups.splice(index);
              this.today_stage_index = index;
            }
          });
          //挑战完所有
          if (this.status == 2) {
            this.showDialog = true;
            this.reason_to_showDialog = 4;
          } else {
            this.getScale();
            //提前初始化第一关数据与图片----------------------避免用户进入第一关等待时间太长
            this.init_first_challenge(1);
          }
        } else {
          this.$toast(res.errorMsg);
        }
      });
    },
    //创建元素
    create_element_diamand() {
      const originalElement = document.getElementById('fly_diamand');
      // 获取原元素的位置和尺寸信息
      const rect = originalElement.getBoundingClientRect();
      // 创建新元素
      const newElement = document.createElement(originalElement.tagName);
      // 设置新元素的属性和样式
      newElement.style.position = 'absolute';
      newElement.style.width = `${rect.width}px`;
      newElement.style.height = `${rect.height}px`;
      newElement.style.top = `${rect.top}px`;
      newElement.style.left = `${rect.left}px`;
      newElement.src = originalElement.src;
      newElement.style.zIndex = '3333';
      newElement.id = 'fly_diamand1';
      // 复制原元素的内容和属性
      newElement.innerHTML = originalElement.innerHTML;
      // 将新元素添加到文档中
      document.body.appendChild(newElement);
    },
    //钻石飞动效
    moveElement(elementId, finalX, finalY) {
      var elem = document.getElementById(elementId);
      var speed_y = 40,
        speed_x = -1;
      this.interval = setInterval(function() {
        finalX += speed_x;
        finalY -= speed_y;
        elem.style.transform = 'translate(' + finalX + 'px, ' + finalY + 'px)';
      }, 100);
    },
    //获取根html的font-size值
    getScale() {
      const rootFZ = window.document.documentElement.style.fontSize;
      console.log(rootFZ);
      this.adapterData(parseFloat(rootFZ));
    },
    //针对1024设计稿图片大小的坐标进行数据加工 适配页面canvas的坐标
    adapterData(rootFZ) {
      this.userPicGroup.forEach(picItem => {
        picItem.postionGroup.forEach(positionItem => {
          positionItem.x = ((400 / 75) * rootFZ * positionItem.x) / 600;
          positionItem.y = ((400 / 75) * rootFZ * positionItem.y) / 600;
        });
      });
    },
    init_first_challenge(processNum) {
      //初始化图片加载完成标志位
      this.both_rendered = false;
      //初始化奖励总数
      this.total_reward = 0;
      // 进入页面初始化进程为1
      this.processNum = processNum;
      //用户点击正确数初始化
      this.clickRightNum = 0;
      //倒计时初始化
      this.time = this.passStageTimeSec;
      //获取第一关页面展示图片数据
      this.picGroup = this.userPicGroup[this.processNum - 1].picGroup;
      //获取第一关命中坐标 数组深拷贝
      this.positionGroup = JSON.parse(
        JSON.stringify(this.userPicGroup[this.processNum - 1].postionGroup)
      );
      //获得该关卡获得钻石数
      this.contPassRewards.forEach(item => {
        if (item.contPassTimes == this.today_stage_index + 1) {
          this.current_reward = item.reward.amount;
          return;
        }
      });
      //在页面绘制图片
      this.drawImage();
    },
    //提交闯关结果
    notice_challenge_result(type) {
      this.showLoading = true;
      isPassStage({
        gameConfigId: this.gameConfigId,
        stageId: this.currentStage,
        isPass: type
      }).then(res => {
        this.showLoading = false;
        if (res.errorCode == 0) {
          this.userTime = res.data.challengeTimes;
          this.total_reward += res.data.reward;
          this.currentStage = res.data.nextStageId;
          //挑战成功
          if (type == 1) {
            //今天已过20关
            if (res.data.nextStageId == 0) {
              this.showDialog = true;
              this.reason_to_showDialog = 3;
              return;
            }
            //每次挑战成功次数加1
            this.user_win_game_num++;
            if (this.user_win_game_num == 10 && !this.isShowAdvice) {
              this.showAdvice = true;
              this.isShowAdvice = true;
            } else {
              //每过一关展示弹窗
              this.showDialog = true;
              this.reason_to_showDialog = 1;
              //过关播放过关音效
              this.$refs.audioGroup.$refs.congratulationAudio.currentTime = 0;
              this.$refs.audioGroup.$refs.congratulationAudio.play();
              //调用飞钻石
              this.$nextTick(() => {
                this.create_element_diamand();
                this.moveElement('fly_diamand1', 20, 20);
              });
              this.$refs.countDown.pause();
            }
          } else {
            //每次挑战失败连续成功数置0
            this.user_win_game_num = 0;
            if (
              this.isFinished &&
              this.total_reward >= 50 &&
              !this.isShowAdvice
            ) {
              console.log(this.isFinished);
              console.log(this.total_reward);
              console.log(this.isShowAdvice);
              this.showAdvice = true;
              this.isShowAdvice = true;
            } else {
              this.showDialog = true;
              //判断用户触发弹窗事件 (有没有挑战次数)
              if (this.userTime > 0) {
                this.reason_to_showDialog = 2;
                //失败播放失败音效
                this.$refs.audioGroup.$refs.gameoverAudio.currentTime = 0;
                this.$refs.audioGroup.$refs.gameoverAudio.play();
              } else {
                this.reason_to_showDialog = 3;
              }
            }
          }
        } else if (res.errorCode == 412001) {
          this.showDialog = true;
          this.reason_to_showDialog = 5;
          this.$refs.countDown.pause();
          getUserDetails().then(res => {
            console.log('获取用户信息接口返回-----------------' + res.errorMsg);
            if (res.errorCode == 0) {
              if (res.data.status == 2) {
                this.over_time_exit = true;
              }
            } else {
              this.$toast(res.errorMsg);
            }
          });
        } else if (res.errorCode == 412002) {
          this.$toast(res.errorMsg);
          location.reload();
          console.log('挑战结果接口返回-----------------' + res.errorMsg);
        }
      });
    },
    //通过进入下一关
    next_challenge() {
      clearInterval(this.interval);
      // this.$refs.countDown.reset()
      this.showDialog = false;
      //图片加载完成标志位还原
      this.both_rendered = false;
      //游戏关数加一
      this.today_stage_index++;
      //获取下一关奖励
      this.contPassRewards.forEach(item => {
        if (item.contPassTimes == this.today_stage_index + 1) {
          this.current_reward = item.reward.amount;
          return;
        }
      });
      //进程数加一
      this.processNum++;
      //获取下一关页面展示图片数据
      console.log(this.userPicGroup);
      this.picGroup = this.userPicGroup[this.processNum - 1].picGroup;
      //获取下一关命中坐标数据  数组深拷贝 避免影响原数组
      this.positionGroup = JSON.parse(
        JSON.stringify(this.userPicGroup[this.processNum - 1].postionGroup)
      );
      //初始化两边画布正确层和错误层
      this.$refs.canvas1.width = this.canvas1W;
      this.$refs.canvas2.width = this.canvas2W;
      //用户点击正确答案数初始化
      this.clickRightNum = 0;
      //通知服务端用户闯关
      this.notice_user_action();
      //每关时间递增初始化
      this.time = (this.remainTime + this.passStageDelayTimeSec) * 1000;
      this.drawImage();
      //初始化页面下方提示命中几次
    },
    //用户使用提示
    useTip() {
      if (this.clickRightNum == this.request_right_num || !this.both_rendered) {
        return;
      }
      this.notice_tip(1);
    },
    //增加时间
    addTime() {
      this.notice_tip(2);
    },
    notice_tip(type) {
      this.showLoading = true;
      useProp({
        gameConfigId: this.gameConfigId,
        stageId: this.currentStage,
        gamePropType: type
      }).then(res => {
        this.showLoading = false;
        if (res.errorCode == 0) {
          //使用提示接口调用返回成功后再操作
          if (type == 1) {
            this.setting1--;
            const tipX = this.positionGroup[0].x;
            const tipY = this.positionGroup[0].y;
            //使用提示命中坐标命中次数加一
            this.clickRightNum += 1;
            this.drawCricle(1, 'setting', { x: tipX, y: tipY });
            this.positionGroup.splice(0, 1);
          } else if (type == 2) {
            this.setting2--;
            this.time = (this.remainTime + this.delayTimeSec) * 1000;
            this.$refs.countDown.reset();
          }
        } else if (res.errorCode == 412001) {
          this.$toast(res.errorMsg);
        } else {
          this.$toast(res.errorMsg);
        }
      });
    },
    onCountDownChange(time) {
      this.remainTime = time.minutes * 60 + time.seconds;
    },
    //调用原生接口返回大厅
    back_to_hall() {
      if (!this.isFinished && this.clickRightNum != this.request_right_num) {
        this.notice_challenge_result(2);
      }
      this.user_off_time = new Date().getTime();
      const user_living_time = (this.user_off_time - this.user_in_time) / 1000;
      this.postUserRemainTime(parseInt(user_living_time));
    },
    //提交埋点数据
    postUserRemainTime(data) {
      finishGame({
        gameConfigId: this.gameConfigId,
        playTime: data
      }).then(res => {
        console.log('获取埋点接口返回-----------------' + res.errorMsg);
        if (res.errorCode == 0) {
          this.$refs.audioGroup.$refs.bgAudio.pause();
          this.$refs.audioGroup.$refs.congratulationAudio.pause();
          this.$refs.audioGroup.$refs.gameoverAudio.pause();
          this.$bridge.callHandler(
            'cancel_mute_game_sound',
            { force: 1 },
            data => {
            }
          );
          this.$bridge.callHandler('close', {}, data => {
          });
        } else {
          this.$toast(res.errorMsg);
          this.$refs.audioGroup.$refs.bgAudio.pause();
          this.$refs.audioGroup.$refs.congratulationAudio.pause();
          this.$refs.audioGroup.$refs.gameoverAudio.pause();
          this.$bridge.callHandler(
            'cancel_mute_game_sound',
            { force: 1 },
            data => {
            }
          );
          this.$bridge.callHandler('close', {}, data => {
          });
        }
      });
    },

    //继续挑战
    continue_game() {
      if (this.clickRightNum == this.request_right_num) {
        //已经通关点击返回按钮
        this.next_challenge();
      } else {
        this.showDialog = false;
        this.$refs.countDown.start();
      }
    },
    //倒计时结束挑战失败--还有挑战次数
    refresh_game() {
      this.showDialog = false;
      this.$refs.countDown.reset();
      this.init_first_challenge(this.processNum);
      //每次挑战调接口通知服务端
      this.notice_user_action();
    },
    //点击返回
    goback() {
      //未进入游戏返回
      if (this.showCover == true) {
        this.$bridge.callHandler(
          'cancel_mute_game_sound',
          { force: 1 },
          data => {
          }
        );
        this.$bridge.callHandler('close', {}, data => {
        });
      } else {
        //已进入游戏返回
        if (this.reason_to_showDialog == 3) {
          return;
        }
        if (!this.isFinished) {
          //游戏时间结束按返回按钮不展示弹窗 ----------已有弹窗
          this.$refs.countDown.pause();
          this.reason_to_showDialog = 0;
          this.showDialog = true;
        }
      }
    },
    //点击刚进入页面弹窗确定按钮
    goAction() {
      if (this.userTime > 0) {
        //初始化第一关页面数据及展示
        this.showCover = false;
        //不足10关或已经挑战完成
        if (this.reason_to_showDialog == 4 || this.reason_to_showDialog == 3) {
          this.showDialog = true;
          return;
        }
        //自动播放背景音乐
        this.$refs.audioGroup.$refs.bgAudio.currentTime = 0;
        this.$refs.audioGroup.$refs.bgAudio.play();
        this.user_in_time = new Date().getTime();
        //每次挑战调接口通知服务端
        this.notice_user_action();
        //解决vant倒计时无法重置问题
        this.auto = true;
        this.$refs.countDown.start();
      }
    },
    notice_user_action() {
      this.showLoading = true;
      challengeStage({
        gameConfigId: this.gameConfigId,
        stageId: this.currentStage
      }).then(res => {
        this.showLoading = false;
        console.log('挑战通知接口返回-----------------' + res.errorMsg);
        if (res.errorCode == 0) {
          this.setting1 = res.data.propInfo.findAnswerTimes;
          this.setting2 = res.data.propInfo.delayTimes;
          this.delayTimeSec = res.data.propInfo.delayTimeSec;
          //获取本关需要多少个正确数量
          this.request_right_num = 2;
          //初始化用户命中
          this.tipsGroup = [];
          for (var i = 0; i < this.request_right_num; i++) {
            this.tipsGroup.push({
              flag: false,
              picUrl: wrong
            });
          }
          //初始化倒计时是否结束
          this.isFinished = false;
          //提前加载下一关图片
          this.loadPic(this.processNum);
        } else if (res.errorCode == 412001) {
          location.reload();
          this.$toast(res.errorMsg);
        } else if (res.errorCode == 412002) {
          this.$toast(res.errorMsg);
          location.reload();
        }
      });
    },
    //倒计时结束
    finished() {
      console.log('finish');
      console.log(this.time);
      this.isFinished = true;
      this.notice_challenge_result(2);
    },
    //初始化画两张图
    drawImage() {
      this.loading_of_pic = true;
      const canvas1 = this.$refs.canvas1;
      const ctx = canvas1.getContext('2d');
      const image = new Image();
      const l = document.getElementById('left');
      this.canvas1W = l.offsetWidth;
      this.canvas1H = l.offsetHeight;
      image.onload = () => {
        ctx.drawImage(image, 0, 0, this.canvas1W, this.canvas1H);
        this.checkBothCanvasLoaded();
      };
      image.setAttribute('crossorigin', '');
      image.crossOrigin = 'anonymous';
      image.src = this.picGroup[0]; // 替换为你的图片URL
      const canvas2 = this.$refs.canvas2;
      const ctx1 = canvas2.getContext('2d');
      const image1 = new Image();
      const r = document.getElementById('right');
      this.canvas2W = r.offsetWidth;
      this.canvas2H = r.offsetHeight;
      image1.onload = () => {
        ctx1.drawImage(image1, 0, 0, this.canvas2W, this.canvas2H);
        this.checkBothCanvasLoaded();
      };
      image1.setAttribute('crossorigin', '');
      image.crossOrigin = 'anonymous';
      image1.src = this.picGroup[1];
    },
    //检查两张图片都加载完成
    checkBothCanvasLoaded() {
      console.log(this.$refs.canvas2.getContext('2d'));
      let canvas1Loaded = this.$refs.canvas1
        .getContext('2d')
        .getImageData(0, 0, this.canvas1W, this.canvas1H)
        .data.findIndex(item => item > 0);
      let canvas2Loaded = this.$refs.canvas2
        .getContext('2d')
        .getImageData(0, 0, this.canvas2W, this.canvas2H)
        .data.findIndex(item => item > 0);
      //任意加载一张图片，进度条至50%
      if (canvas1Loaded != -1 || canvas2Loaded != -1) {
        this.$refs.homePageDialog.progress = 50; // 执行后续操作
      }
      //加载完两张图片
      if (canvas1Loaded != -1 && canvas2Loaded != -1) {
        this.$refs.homePageDialog.progress = 100;
        this.loading_of_pic = false;
        this.both_rendered = true;
        //第1 关在此代码段不启动倒计时
        if (this.processNum != 1) {
          //解决vant倒计时无法重置问题
          this.auto = true;
          this.$refs.countDown.start();
        }
        console.log('两个canvas画的图片都渲染完成');
        // 执行后续操作
      }
    },
    //点击获取坐标范围
    getCanvasCoordinates(event) {
      if (!this.both_rendered) {
        console.log('我就不给你点');
        return;
      }
      const canvas5 = this.$refs.canvas7;
      const canvas6 = this.$refs.canvas8;
      //判断点击哪个canvas
      const isCanvas1 =
        event.target === canvas5 || canvas5.contains(event.target);
      const isCanvas2 =
        event.target === canvas6 || canvas6.contains(event.target);
      if (isCanvas1) {
        const rect = canvas5.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        console.log('Clicked at:', x, y);
        //给定坐标只要有任何一个在点击坐标半径30范围内就正确
        let inCircleIndex = this.positionGroup.findIndex(
          item => (item.x - x) ** 2 + (item.y - y) ** 2 < 20 ** 2
        );
        if (inCircleIndex != -1) {
          //命中一次，当前关数命中次数加一
          this.clickRightNum++;
          this.drawCricle(1, 'leftCan', this.positionGroup[inCircleIndex]);
          //点击正确一次则删除数组中命中的给定坐标，防止多次点击
          this.positionGroup.splice(inCircleIndex, 1);
        } else {
          this.drawCricle(2, 'leftCan');
        }
      } else if (isCanvas2) {
        const rect = canvas6.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        let inCircleIndex = this.positionGroup.findIndex(
          item => (item.x - x) ** 2 + (item.y - y) ** 2 < 20 ** 2
        );
        if (inCircleIndex != -1) {
          //命中一次，当前关数命中次数加一
          this.clickRightNum++;
          this.drawCricle(1, 'rightCan', this.positionGroup[inCircleIndex]);
          //点击正确一次则删除数组中命中的给定坐标，防止多次点击
          this.positionGroup.splice(inCircleIndex, 1);
        } else {
          this.drawCricle(2, 'rightCan');
        }
      }
    },
    //点击显示
    drawCricle(type, from, obj) {
      //从提示过来画红圈
      if (type == 1 && from == 'setting') {
        console.log('type======' + type);
        console.log(
          'x=' +
          (obj.x * 1024) /
          parseFloat(window.document.documentElement.style.fontSize) /
          5.33333333 +
          ',y=' +
          (obj.y * 1024) /
          parseFloat(window.document.documentElement.style.fontSize) /
          5.33333333
        );
        //画布1显示红圈
        const canvas1 = this.$refs.canvas1;
        const ctx1 = canvas1.getContext('2d');
        const image1 = new Image();
        image1.onload = () => {
          ctx1.drawImage(image1, obj.x - 23, obj.y - 23, 46, 46);
        };
        image1.src = this.pick_right_url;
        //画布2显示红圈
        const canvas2 = this.$refs.canvas2;
        const ctx2 = canvas2.getContext('2d');
        const image2 = new Image();
        image2.onload = () => {
          ctx2.drawImage(image2, obj.x - 23, obj.y - 23, 46, 46);
        };
        image2.src = this.pick_right_url;
        //点击正确播放音效
        this.$refs.audioGroup.$refs.correctAudio.currentTime = 0;
        this.$refs.audioGroup.$refs.correctAudio.play();
        return;
      }
      //点击左图点击正确显示红圈
      if (type == 1 && from == 'leftCan') {
        //点击左图正确播放音效
        this.$refs.audioGroup.$refs.correctAudio.currentTime = 0;
        this.$refs.audioGroup.$refs.correctAudio.play();
        //画布1显示红圈
        const canvas1 = this.$refs.canvas1;
        const ctx1 = canvas1.getContext('2d');
        const image1 = new Image();
        image1.onload = () => {
          ctx1.drawImage(image1, obj.x - 23, obj.y - 23, 46, 46);
        };
        image1.src = this.pick_right_url;
        //画布2显示红圈
        const canvas2 = this.$refs.canvas2;
        const ctx2 = canvas2.getContext('2d');
        const image2 = new Image();
        image2.onload = () => {
          ctx2.drawImage(image2, obj.x - 23, obj.y - 23, 46, 46);
        };
        image2.src = this.pick_right_url;
      } else if (type == 1 && from == 'rightCan') {
        //点击右图正确播放音效
        this.$refs.audioGroup.$refs.correctAudio.currentTime = 0;
        this.$refs.audioGroup.$refs.correctAudio.play();
        //点击右图点击正确显示红圈
        //画布2显示红圈
        const canvas2 = this.$refs.canvas2;
        const ctx2 = canvas2.getContext('2d');
        const rect2 = canvas2.getBoundingClientRect();
        const image1 = new Image();
        image1.onload = () => {
          ctx2.drawImage(image1, obj.x - 23, obj.y - 23, 46, 46);
        };
        image1.src = this.pick_right_url;
        //画布1显示红圈
        const canvas1 = this.$refs.canvas1;
        const ctx1 = canvas1.getContext('2d');
        const image2 = new Image();
        image2.onload = () => {
          ctx1.drawImage(image2, obj.x - 23, obj.y - 23, 46, 46);
        };
        image2.src = this.pick_right_url;
      } else if (type == 2 && from == 'leftCan') {
        //点击左图错误扣2s
        // if((this.remainTime - 1) * 1000>=0){ //处理多次倒计时结束事件
        this.time = (this.remainTime - 1) * 1000;
        this.$refs.countDown.reset();
        // }
        // this.time = (this.remainTime - 1) * 1000
        // this.$refs.countDown.reset()
        //点击左图点击错误播放音乐
        this.$refs.audioGroup.$refs.wrongAudio.currentTime = 0;
        this.$refs.audioGroup.$refs.wrongAudio.play();
        //点击左图点击错误显示叉号
        //画布1显示叉号
        const canvas5 = this.$refs.canvas5;
        const ctx5 = canvas5.getContext('2d');
        const rect5 = canvas5.getBoundingClientRect();
        const x5 = event.clientX - rect5.left;
        var y5 = event.clientY - rect5.top;
        const image1 = new Image();
        image1.onload = () => {
          ctx5.drawImage(image1, x5 - 23, y5 - 23, 46, 46);
        };
        image1.src = this.pick_wrong_url;
        setTimeout(() => {
          ctx5.clearRect(0, 0, canvas5.width, canvas5.height);
        }, 1000);
        //显示-2s
        const canvas7 = this.$refs.canvas7;
        const ctx7 = canvas7.getContext('2d');
        const rect7 = canvas7.getBoundingClientRect();
        const x7 = event.clientX - rect7.left;
        var y7 = event.clientY - rect7.top;
        const distance = y7;
        const imageTime = new Image();
        imageTime.onload = () => {
          ctx7.drawImage(imageTime, x7 - 26, y7 - 47, 52, 26);
        };
        imageTime.src = this.animationTime_url;

        //-2s动画效果
        function animate() {
          // 清除画布
          ctx7.clearRect(0, 0, canvas7.width, canvas7.height);
          // 减少y坐标以向上移动图片
          y7 -= 1;
          // 重新绘制图片
          ctx7.drawImage(imageTime, x7 - 26, y7 - 47, 52, 26);
          // 如果图片还没有移出画布，继续动画
          if (y7 > distance / 2) {
            requestAnimationFrame(animate);
          } else {
            ctx7.clearRect(0, 0, canvas7.width, canvas7.height);
          }
        }

        setTimeout(() => {
          requestAnimationFrame(animate);
        }, 1000);
        //点击错误显示叉号
        //画布2显示叉号
        const canvas6 = this.$refs.canvas6;
        const ctx6 = canvas6.getContext('2d');
        const x6 = event.clientX - rect5.left;
        const y6 = event.clientY - rect5.top;
        const image2 = new Image();
        image2.onload = () => {
          ctx6.drawImage(image2, x6 - 23, y6 - 23, 46, 46);
        };
        image2.src = this.pick_wrong_url;
        //点击错误两秒后清除图层
        setTimeout(() => {
          ctx6.clearRect(0, 0, canvas6.width, canvas6.height);
        }, 1000);
      } else {
        //点击右图错误扣2s
        this.time = (this.remainTime - 1) * 1000;
        this.$refs.countDown.reset();
        //点击右图点击错误播放音乐
        this.$refs.audioGroup.$refs.wrongAudio.currentTime = 0;
        this.$refs.audioGroup.$refs.wrongAudio.play();
        //点击右图点击错误显示叉号
        //画布2显示叉号
        const canvas6 = this.$refs.canvas6;
        const ctx6 = canvas6.getContext('2d');
        const rect6 = canvas6.getBoundingClientRect();
        const x6 = event.clientX - rect6.left;
        var y6 = event.clientY - rect6.top;
        const image1 = new Image();
        image1.onload = () => {
          ctx6.drawImage(image1, x6 - 23, y6 - 23, 46, 46);
        };
        image1.src = this.pick_wrong_url;
        setTimeout(() => {
          ctx6.clearRect(0, 0, canvas6.width, canvas6.height);
        }, 500);
        //显示-2s
        const canvas8 = this.$refs.canvas8;
        const ctx8 = canvas8.getContext('2d');
        const rect8 = canvas8.getBoundingClientRect();
        const x8 = event.clientX - rect8.left;
        var y8 = event.clientY - rect8.top;
        const distance = y8;
        const imageTime = new Image();
        imageTime.onload = () => {
          ctx8.drawImage(imageTime, x8 - 26, y8 - 47, 52, 26);
        };
        imageTime.src = this.animationTime_url;

        //-2s动画效果
        function animate() {
          // 清除画布
          ctx8.clearRect(0, 0, canvas8.width, canvas8.height);
          // 减少y坐标以向上移动图片
          y8 -= 1;
          // 重新绘制图片
          ctx8.drawImage(imageTime, x8 - 26, y8 - 47, 52, 26);
          // 如果图片还没有移出画布，继续动画
          if (y8 > distance / 2) {
            requestAnimationFrame(animate);
          } else {
            ctx8.clearRect(0, 0, canvas8.width, canvas8.height);
          }
        }

        setTimeout(() => {
          requestAnimationFrame(animate);
        }, 500);
        //画布1显示叉号
        const canvas5 = this.$refs.canvas5;
        const ctx5 = canvas5.getContext('2d');
        const x5 = event.clientX - rect6.left;
        const y5 = event.clientY - rect6.top;
        const image2 = new Image();
        image2.onload = () => {
          ctx5.drawImage(image1, x5 - 23, y5 - 23, 46, 46);
        };
        image2.src = this.pick_wrong_url;
        //点击错误两秒后清除图层
        setTimeout(() => {
          ctx5.clearRect(0, 0, canvas5.width, canvas5.height);
        }, 1000);
        //点击错误显示叉号
      }
    }
  }
};
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
